package daobeauty.util;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Created 15.09.2008
 * @author M. Serhat Cinar
 *
 */
public class LinkedListStack<O> implements Stack<O> {
	@SuppressWarnings("unused")
	private static final Log LOG = LogFactory.getLog(LinkedListStack.class);
	
	private final LinkedList<O> stack = new LinkedList<O>();
	
	/* (non-Javadoc)
	 * @see daobeauty.util.Stack#push(O)
	 */
	public void push(O element){
		stack.add(element);
	}
	
	/* (non-Javadoc)
	 * @see daobeauty.util.Stack#pop()
	 */
	public O pop(){
		if (stack.isEmpty()){
			throw new NoSuchElementException();
		}
		final O last = stack.removeLast();
		return last;
	}
	
	/* (non-Javadoc)
	 * @see daobeauty.util.Stack#peek()
	 */
	public O peek(){
		if (stack.isEmpty()){
			throw new NoSuchElementException();
		}
		final O last = stack.getLast();
		return last;
	}
	
	/* (non-Javadoc)
	 * @see daobeauty.util.Stack#isEmpty()
	 */
	public boolean isEmpty(){
		return stack.isEmpty();
	}
	
	/* (non-Javadoc)
	 * @see daobeauty.util.Stack#addFirst(O)
	 */
	public void addFirst(O element){
		stack.addFirst(element);
	}
	
	/* (non-Javadoc)
	 * @see daobeauty.util.Stack#size()
	 */
	public int size(){
		return stack.size();
	}
	
	/* (non-Javadoc)
	 * @see daobeauty.util.Stack#iterator()
	 */
	public Iterator<O> iterator(){
		// TODO falsche reihenfolge!
		return stack.iterator();
	}
	
	/* (non-Javadoc)
	 * @see daobeauty.util.Stack#toString()
	 */
	public String toString(){
		final StringBuilder sb = new StringBuilder();
		sb.append("["+stack.size()+"]{");
		final Iterator<O> iter = iterator();
		while (iter.hasNext()){
			sb.append("\""+String.valueOf(iter.next())+"\"");
			if (iter.hasNext()){
				sb.append(", ");
			}
		}
		sb.append("}");
		return sb.toString();
	}
}
